package com.yunchao.feature.business.data.datasource.database.model

import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.yunchao.feature.business.domain.model.BusinessInfoModel

@Entity(tableName = "business_info")
@TypeConverters(PackInfoEntityConverter::class)
internal data class BusinessInfoEntityModel(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val tranTypeID: String, //    String 17 N  交易代码
    val tranID: String,//   String 13 N  业务序号
    val chkUserId: String,//    String 19 Y  复核人id
    val sequency: String,// String 50 N  交易流水号
    val giveDataTime: String,// String 14 N  交易时间
    val giveOperator: String,// String 19 N  操作人id
    val cardID: String,//   String 20 Y  操作人卡号
    val packInfoList: List<BusinessPackEntityModel>,
    val busiInfoList: List<BusinessPackEntityModel>,
    val packInfoPayloads: List<BusinessPackEntityModel>,
)

internal fun BusinessInfoEntityModel.toDomainModel() = BusinessInfoModel(
    tranTypeID = tranTypeID,
    tranID = tranID,
    chkUserId = chkUserId,
    sequency = sequency,
    giveDataTime = giveDataTime,
    giveOperator = giveOperator,
    cardID = cardID,
    packInfoList = packInfoList.map { it.toDomainModel() },
    busiInfoList = busiInfoList.map { it.toDomainModel() },
    packInfoPayloads = packInfoPayloads.map { it.toDomainModel() },
)



internal class PackInfoEntityConverter {

    @TypeConverter
    fun stringToList(data: String?): List<BusinessPackEntityModel> = data?.let {
        val token = object : TypeToken<List<BusinessPackEntityModel>>() {}
        Gson().fromJson(it, token.type)
    } ?: emptyList()

    @TypeConverter
    fun listToString(someObjects: List<BusinessPackEntityModel>): String =
        Gson().toJson(someObjects)

}
